package com.maoyu.cloud.user.service.impl;

import com.maoyu.cloud.exception.EmailExitException;
import com.maoyu.cloud.exception.MobileExitException;
import com.maoyu.cloud.exception.UserNameExitException;
import com.maoyu.cloud.login.entity.LoginUserEntity;
import com.maoyu.cloud.mybatis.entity.PtUserEntity;
import com.maoyu.cloud.mybatis.entity.ZtreeEntity;
import com.maoyu.cloud.mybatis.flexigrid.PadingRstType;
import com.maoyu.cloud.mybatis.flexigrid.PagingBean;
import com.maoyu.cloud.spring.util.CloudUtil;
import com.maoyu.cloud.user.entity.SearchUserEntity;
import com.maoyu.cloud.user.entity.UserEntity;
import com.maoyu.cloud.user.exception.PasswordError;
import com.maoyu.cloud.user.repository.UserInfoDao;
import com.maoyu.cloud.user.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("userService")
public class UserServiceImpl implements UserService {
    private final Logger logger = LogManager.getLogger(this.getClass());
    @Resource
    private UserInfoDao userInfoDao;

    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    private MessageSource messageSource;
    @Override
    public List<PtUserEntity> queryUserListByName(SearchUserEntity search)
    {
        return userInfoDao.queryUserInfoList(search);
    }

    @Override
    public void modifyPassword(String oldPassword, String newPassword) throws PasswordError {
        LoginUserEntity loginUserEntity = (LoginUserEntity)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String encodeOldPassword = passwordEncoder.encode(oldPassword);
        PtUserEntity ptUserEntity = userInfoDao.queryUserByUuid(loginUserEntity.getUserUuid(),encodeOldPassword);
        if (ptUserEntity == null) {
            throw new PasswordError("old password error");
        }
        String encodeNewPassword = passwordEncoder.encode(newPassword);
        userInfoDao.modifyPassword(encodeNewPassword, loginUserEntity.getUserUuid());
    }

    @Override
    public PadingRstType<PtUserEntity> getUserInfolistByPage(SearchUserEntity search, PagingBean paging) {
        paging.deal(PtUserEntity.class);
        PadingRstType<PtUserEntity> ptUserEntityPadingRstType = new PadingRstType<>();
        List<PtUserEntity> list = userInfoDao.getUserInfolistByPage(search,paging);
        Integer total = userInfoDao.getUserInfolistTotal(search);
        ptUserEntityPadingRstType.setPage(paging.getPage());
        ptUserEntityPadingRstType.setRawRecords(list);
        ptUserEntityPadingRstType.setTotal(total);
        ptUserEntityPadingRstType.putItems();
        return ptUserEntityPadingRstType;
    }

    @Override
    public void addUser(UserEntity userEntity) throws UserNameExitException, EmailExitException, MobileExitException {
        Integer count = userInfoDao.queryUserCountByName(userEntity.getUserName());
        if (count > 0) {
            throw new UserNameExitException("userName:" + userEntity.getUserName());
        }
        count = userInfoDao.queryUserCountByEmial(userEntity.getEmail());
        if (count > 0) {
            throw new EmailExitException("email:" + userEntity.getEmail());
        }

        String mobile = userEntity.getMobile();
        if (mobile != null && !mobile.equals("")) {
            count = userInfoDao.queryUserCountByMobile(userEntity.getMobile());
            if (count > 0) {
                throw new MobileExitException("mobile:" + userEntity.getMobile());
            }
        }
        userEntity.setUserUuid(CloudUtil.generateUuid()); // 设置UUid
        String password = passwordEncoder.encode(userEntity.getPassword()); // 加密
        userEntity.setPassword(password);
        userInfoDao.addUser(userEntity);

    }

    @Override
    public UserEntity queryUserInfoById(String userUuid) {
        return userInfoDao.queryUserInfoById(userUuid);
    }

    @Override
    public void updateUserInfo(UserEntity userEntity) throws UserNameExitException, EmailExitException, MobileExitException {
        Integer count = userInfoDao.queryUserCountByNameNotId(userEntity.getUserName(),userEntity.getUserUuid());
        if (count > 0) {
            throw new UserNameExitException("userName:" + userEntity.getUserName());
        }
        count = userInfoDao.queryUserCountByEmialNotId(userEntity.getEmail(),userEntity.getUserUuid());
        if (count > 0) {
            throw new EmailExitException("email:" + userEntity.getEmail());
        }

        String mobile = userEntity.getMobile();
        if (mobile != null && !mobile.equals("")) {
            count = userInfoDao.queryUserCountByMobileNotId(userEntity.getMobile(),userEntity.getUserUuid());
            if (count > 0) {
                throw new MobileExitException("mobile:" + userEntity.getMobile());
            }
        }
        userInfoDao.updateUserInfo(userEntity);
    }

    @Override
    public void deleteUserInfoByIds(String userUuids) {
        String[] userUuidsArray = userUuids.split(",");
        userInfoDao.deleteUserInfoByIds(userUuidsArray);
    }

    @Override
    public List<ZtreeEntity> queryRoleZtreeByUserId(String userUuid) {
        List<ZtreeEntity> ztreeEntityList = queryRoleZtreeAll();
        List<String> selectRoleIdList = userInfoDao.queryRoleZtreeListByUserId(userUuid);

        for(ZtreeEntity roleEntity:ztreeEntityList) {
            for(String roleId:selectRoleIdList)
            {
                if(roleId.equals(roleEntity.getId())){
                    roleEntity.setChecked(true);
                    break;
                }
            }
        }
        return ztreeEntityList;
    }

    @Override
    public void saveRoleRelUser(String userUuidArray, String roleArray) {
        String[] userUuids = userUuidArray.split(",");
        String[] rolesArray = roleArray.split(",");
        for (String userUuid : userUuids) {
            userInfoDao.deleteRoleByUser(userUuid);
            for (String roleUuid : rolesArray) {
                userInfoDao.insertRoleByUser(userUuid, roleUuid);
            }
        }


    }

    @Override
    public List<ZtreeEntity> queryRoleZtreeAll() {
        List<ZtreeEntity> ztreeEntityList = userInfoDao.queryRoleZtreeAll();

        ZtreeEntity ztreeEntity1 = new ZtreeEntity();
        String message = messageSource.getMessage("user.role.manager", null, LocaleContextHolder.getLocale());
        ztreeEntity1.setName(message);
        ztreeEntity1.setId("-1");
        ztreeEntity1.setpId("-2");
        ztreeEntityList.add(ztreeEntity1);
        return ztreeEntityList;
    }
    @Override
    public void resetPassword(String userUuidArray, String password) {
        String encPassword = passwordEncoder.encode(password);
        String[] userUuids = userUuidArray.split(",");
        userInfoDao.resetPasswordByIds(userUuids,encPassword);

    }

    /**
     * 注册用户
     * @param user
     */
    @Override
    public void save(PtUserEntity user) {
        user.setUserUuid(CloudUtil.generateUuid());
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        userInfoDao.save(user);
    }

}